package com.jike.jkgame;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.jike.jkgame.data.ResourceType;
import com.jike.jkgame.data.UserResource;
import com.jike.jkgame.network.data.ResourceResultData;
import com.jike.jkgame.widget.CoverFlow;

public class ShowResourceActivity extends Activity implements OnClickListener {
	private CoverFlow mCoverFlow;
	private CoverAdapter mCoverAdapter;
	private ProgressBar mConectingPb;
	private WheelView mCategoryWheel;
	private Button mSelectBtn;
	
	private ResViewHolder mResViewHolder;

	private CategorySlotAdapter mCategoryAdaper = new CategorySlotAdapter();
	private ResourceType mResType;
	private final String mCategories[] = Utilis
			.getResStringArrary(R.array.resource_type);
	private UserResource[] mResources;
	private int mCurResIdx = -1;
	
	private Handler mHandler = new Handler();

	// Wheel scrolled listener
	private OnWheelScrollListener mSlotScrolledListener = new OnWheelScrollListener() {
		public void onScrollingStarted(WheelView wheel) {
		}

		public void onScrollingFinished(WheelView wheel) {

		}
	};

	// Wheel changed listener
	private OnWheelChangedListener mSlotChangedListener = new OnWheelChangedListener() {
		public void onChanged(WheelView wheel, int oldValue, int newValue) {
			mResType = ResourceType.values()[newValue];
			mCategoryWheel.requestLayout();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_resource_layout);
		
		Intent intent = getIntent();
		
		mResType = (ResourceType) intent.getSerializableExtra(Global.Keys.RES_TYPE);
		
		mCoverFlow = (CoverFlow) findViewById(R.id.cf_reses);

		mConectingPb = (ProgressBar) findViewById(R.id.pb_conecting);
		
		mResViewHolder = new ResViewHolder();
		mResViewHolder.nameTv = (TextView) findViewById(R.id.tv_name);
		mResViewHolder.starRb = (RatingBar) findViewById(R.id.rb_starts);
		mResViewHolder.levelTv = (TextView) findViewById(R.id.tv_level);
		mResViewHolder.expPb = (ProgressBar) findViewById(R.id.pb_res_level);
		mResViewHolder.valueTv = (TextView) findViewById(R.id.tv_res_value);

		mCoverAdapter = new CoverAdapter(this);

		// coverImageAdapter.createReflectedImages();

		mCoverFlow.setAdapter(mCoverAdapter);
		mCoverFlow.setOnItemSelectedListener(new OnCoverItemSelectListener());
		mCoverFlow.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO
			}

		});
		mCoverFlow.setSpacing(-25);
		mCoverFlow.setSelection(0, true);
		mCoverFlow.setAnimationDuration(1000);

		mSelectBtn = (Button) findViewById(R.id.btn_select);
		mSelectBtn.setOnClickListener(this);

		mCategoryWheel = (WheelView) findViewById(R.id.slot_category);

		mCategoryWheel.setViewAdapter(mCategoryAdaper);
		mCategoryWheel.setCurrentItem(mResType.ordinal());
		mCategoryWheel.setCyclic(true);
		mCategoryWheel.setEnabled(true);
		mCategoryWheel.setVisibleItems(3);
		mCategoryWheel.addScrollingListener(mSlotScrolledListener);
		mCategoryWheel.addChangingListener(mSlotChangedListener);
		mCategoryWheel.setEnabled(false);
		
		getResouces(mResType);
	}

	public class OnCoverItemSelectListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int postion, long id) {
			updateResViews(postion);

		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {

		}
	}

	public class CoverAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;

		public CoverAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			if (mResources == null) {
				return 0;
			} else {
				return mResources.length;
			}
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			// Use this code if you want to load from resources
			ImageView i = new ImageView(mContext);

			if (position == 4) {
				i.setImageResource(R.drawable.ic_launcher);
			} else {
				i.setImageResource(R.drawable.bigsword);
			}

			i.setLayoutParams(new CoverFlow.LayoutParams(
					CoverFlow.LayoutParams.WRAP_CONTENT, 300));
			i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

			// Make sure we set anti-aliasing otherwise we get jaggies
			BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
			drawable.setAntiAlias(true);
			return i;

		}

		/**
		 * Returns the size (0.0f to 1.0f) of the views depending on the
		 * 'offset' to the center.
		 */
		public float getScale(boolean focused, int offset) {
			/* Formula: 1 / (2 ^ offset) */
			return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
		}

	}
	
	private UserResource getCurrentResource() {
		if(mResources !=null && mCurResIdx >= 0 && mCurResIdx < mResources.length) {
			return mResources[mCurResIdx];
		}
		return null;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_select: {
			UserResource res = getCurrentResource();
			if (res != null) {
				Intent intent = new Intent();
				intent.putExtra(Global.Keys.RES_DATA, res);
				setResult(Activity.RESULT_OK, intent);
			} else {
				setResult(Activity.RESULT_CANCELED);
			}
			finish();
			break;
		}
		default:
			break;
		}

	}

	private class CategorySlotAdapter extends AbstractWheelAdapter {

		@Override
		public int getItemsCount() {
			return mCategories.length;
		}

		final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			TextView tv;
			if (cachedView != null) {
				tv = (TextView) cachedView;
			} else {
				tv = new TextView(JKApp.get());
				tv.setGravity(Gravity.CENTER);
			}

			if (index == mResType.ordinal()) {
				tv.setTextSize(20);
			} else {
				tv.setTextSize(16);
			}
			tv.setText(mCategories[index]);
			tv.setLayoutParams(params);
			return tv;
		}
	}
	
	private void updateResViews(int idx) {
		mCurResIdx = idx;
		UserResource res = mResources[idx];
		mResViewHolder.nameTv.setText(String.valueOf(res.tid));
		mResViewHolder.levelTv.setText("LV"+res.level);
		mResViewHolder.starRb.setRating(res.star);
		mResViewHolder.expPb.setProgress(res.exp);
		
		int drawableId;
		int value;
		if (res.attack > 0) {
			value = res.attack;
			drawableId = R.drawable.ic_attack;
		} else {
			value = res.defense;
			drawableId = R.drawable.ic_defense;
		}
		mResViewHolder.valueTv.setText(String.valueOf(value));
		Drawable img = getResources().getDrawable(drawableId);
		mResViewHolder.valueTv.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );
	}
	
	private void getResouces(ResourceType type) {
		GetResourceListTask task = new GetResourceListTask();
		task.execute(type);
	}
	
	private class GetResourceListTask extends GetResourcesTask {

		@Override
		protected void onPostExecute(ResourceResultData result) {
			super.onPostExecute(result);
			mConectingPb.setVisibility(View.GONE);
			
			if (result.opcode == 0) {
				mResources = result.res;
				mCoverAdapter.notifyDataSetChanged();
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mConectingPb.setVisibility(View.VISIBLE);
		}
		
	}
	
	private static class ResViewHolder {
		public TextView nameTv;
		public RatingBar starRb;
		public TextView levelTv;
		public ProgressBar expPb;
		public TextView valueTv;
	}
	
}
